package com.park.web.controller.user;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.park.client.model.pub.LinkModel;
import com.park.client.model.user.IntegralIncomeModel;
import com.park.client.model.user.SignInModel;
import com.park.client.model.user.SignModel;
import com.park.client.model.user.UserAttentionModel;
import com.park.client.model.user.UserModel;
import com.park.client.service.article.ArticleCollectService;
import com.park.client.service.pub.LinkService;
import com.park.client.service.user.IntegralIncomeService;
import com.park.client.service.user.SignInService;
import com.park.client.service.user.SignService;
import com.park.client.service.user.UserAttentionService;
import com.park.client.service.user.UserMsgService;
import com.park.client.service.user.UserService;
import com.park.common.constant.Constant;
import com.park.common.file.FileUtil;
import com.park.common.file.ImageUtil;
import com.park.common.util.MD5;
import com.park.common.util.Result;
import com.park.service.impl.websocket.MessageHandler;
import com.park.web.contant.Global;
import com.park.web.controller.BaseController;
import com.park.web.enums.UserAttentionEnum;
import com.park.web.util.SessionUtil;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

	@Autowired
	private UserService userService;
	@Autowired
	private MessageHandler messageHandler;
	@Autowired
	private ArticleCollectService articleCollectService;
	@Autowired
	private SignService signService;
	@Autowired
	private SignInService signInService;
	@Autowired
	private IntegralIncomeService incomeService;
	@Autowired
	private UserAttentionService userAttentionService;
	@Autowired
	private UserMsgService userMsgService;
	@Autowired
	private LinkService linkService;
	
	@RequestMapping("/list")
	@ResponseBody
	public Result<List<UserModel>> list(){
		Result<List<UserModel>> result = new Result<>(true);
		result.setObj(userService.selectAll());
		return result;
	}
	
	@RequestMapping("/userLogin")
	public String userLogin(HttpSession session){
		Result<List<UserModel>> result = new Result<>();
		result.setObj(userService.selectAll());
		messageHandler.sendMessage(result);
		return Global.USER_PATH+"success";
	}
	
	/**
	 * 积分页面
	 */
	@RequestMapping("myIntegral")
	public String myIntegral(HttpSession session,HttpServletRequest request){
		return Global.USER_PATH+"user/myIntegral";
	} 
	
	/**
	 *个人主页
	 */
	@RequestMapping("index")
	public String index(HttpSession session,HttpServletRequest request){
		UserModel user = SessionUtil.getSessionUser(session);
		List<LinkModel> linkLists = linkService.selectAll();//友情链接
		request.setAttribute("linkLists", linkLists);
//		List<ArticleCollect> collects =  articleCollectService.list(user.getId());//我的收藏
//		request.setAttribute("collects", collects);
		SignModel sign  = signService.selectLatestSign(user.getId());//我的动态
		request.setAttribute("sign", sign);
		int total = userMsgService.getMsgTotal(user.getId());//未读消息数量
		request.setAttribute("total", total);
		
		//签到
		SignInModel record = new SignInModel();
		record.setCreater(user.getId());
		record.setCreateDate(new Date());
		SignInModel signIn = signInService.selectByUserId(record);
		request.setAttribute("signIn", signIn);
		
		//我关注的
		UserAttentionModel userAttention = new UserAttentionModel();
		userAttention.setAttentionType(UserAttentionEnum.ATTENTION.code);
		userAttention.setCreater(user.getId());
		List<UserAttentionModel> userAttentions =  userAttentionService.selectAllAttentions(userAttention);
		request.setAttribute("attentionTotal", userAttentions.size());
		//关注我的
		userAttention = new UserAttentionModel();
		userAttention.setAttentionType(UserAttentionEnum.ATTENTION_ME.code);
		userAttention.setUserAttentionId(user.getId());
		userAttentions =  userAttentionService.selectAllAttentions(userAttention);
		request.setAttribute("attentionMeTotal", userAttentions.size());
		return Global.USER_PATH+"index";
	} 
	
	/**
	 *保存个人图像
	 */
	@RequestMapping("uploadPicture")
	public String uploadPictureSave(@RequestParam("picture") MultipartFile file,HttpSession session,HttpServletRequest request){
		try {
			UserModel user = SessionUtil.getSessionUser(session);
			InputStream is =  file.getInputStream();
			user.setPicture(FileUtil.getBytes(is));
			userService.uploadPicture(user);
		} catch (IOException e) {
			logger.error("上传图像出错",e);
		}
		return  "redirect:index";
	}
	
	
	@RequestMapping("showPicture")
	public void showPicture(@RequestParam("id")Long id,HttpServletResponse response) throws IOException{
		UserModel user =	userService.selectByPrimaryKey(id);
		byte[] data = user.getPicture();
		ImageUtil.writeToPicture(data, response);
}
	
	/**
	 *个人资料
	 */
	@RequestMapping("personData")
	public String personData(HttpSession httpSession,HttpServletRequest request){
		return  Global.USER_PATH+"user/personData";
	}
	
	/**
	 *个人动态
	 */
	@RequestMapping("personDynamic")
	public String personDynamic(HttpSession httpSession,HttpServletRequest request){
		return  Global.USER_PATH+"user/personDynamic";
	}
	
	/**
	 *个人心情
	 */
	@RequestMapping("personMood")
	public String personMood(HttpSession httpSession,HttpServletRequest request){
		return  Global.USER_PATH+"user/personMood";
	}
	
	
	/**
	 *修改密码页面
	 */
	@RequestMapping("updatePwd")
	public String updatePwd(HttpSession httpSession,HttpServletRequest request){
		return  Global.USER_PATH+"user/updatePwd";
	}
	
	/**
	 *修改密码保存
	 */
	@RequestMapping("updatePwdSave")
	public String updatePwdSave(UserModel user,String pwd,HttpSession session,HttpServletRequest request){
		user.setPassword(MD5.md5(pwd));
		user.setId(SessionUtil.getUserID(session));
		boolean success =  userService.updatePwd(user);
		if(success){
			//修改成功，清楚session，必须重登
			session.invalidate();
			return"redirect:/public/user/login";
		}else{
			request.setAttribute("msg", "修改密码失败!");
			return Global.USER_PATH+"account/updatePwd";
		}
	}
	
	/**
	 * 签到
	 */
	@RequestMapping("signIntegral")
	@ResponseBody
	public Result<String> signIntegral(HttpSession session){
		Result<String> result = new Result<>(true);
		UserModel user = (UserModel) session.getAttribute("user");
		SignInModel record = new SignInModel();
		record.setCreater(user.getId());
		record.setCreateDate(new Date());
		SignInModel s = signInService.selectByUserId(record);
		if(s != null){
			result.setSuccess(false);
			return result;
		}
		try {
			//签到记录
			signInService.insertSelective(record);
			//增加积分
			user.setIntegral(user.getIntegral()+1);
			userService.updateByPrimaryKeySelective(user);
			//积分收入明细记录
			IntegralIncomeModel income = new IntegralIncomeModel();
			income.setCreateDate(new Date());
			income.setIntegral(1);
			income.setUserId(user.getId());
			income.setSource(1);
			incomeService.insertSelective(income);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("签到失败");
		}
		return result;
	}
	
	/**
	 *扫码支付完毕后
	 */
	@RequestMapping("payMoneyBack")
	@ResponseBody
	public Result<Boolean> payMoneyBack(Long userId){
		Result<Boolean> result = new Result<>(true);
		UserModel user = userService.selectByPrimaryKey(userId);
		boolean success = false;
		if(user.getDisabled() == 0){//判断账号是否被冻结，防止恶意操作
			result.setMessage(Constant.FAIL_FREEZE_MSG);
		}else{
			success =  userService.updateByPrimaryKeySelective(user);
			if(success){
				result.setMessage(Constant.SUCCESS_PAY_MSG);
			}else{
				result.setMessage(Constant.SUCCESS_PAY_MSG);
			}
		}
		result.setSuccess(success);
		return result;
	}
	
	/**
	 * 退出
	 */
	@RequestMapping("logout")
	public String logout(HttpSession session,HttpServletRequest request){
		UserModel user = (UserModel) session.getAttribute("user");
		if(user != null){
			session.invalidate();
		}
		return  "redirect:/public/index";
	}
	
}
